/**
 * 语言编辑页面
 */

import React, { useState, useEffect } from 'react';
import { Typography, Card, Table, Button, Input, Space, Tag, Modal, message, Form, Statistic, Tabs, Alert } from 'antd';
import { 
  SaveOutlined, 
  ArrowLeftOutlined, 
  DownloadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
  CodeOutlined,
  CopyOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import styled from 'styled-components';
import { themeConfig } from '../theme/themeConfig';
import { Button as CustomButton } from '../components/ui/Button';
import { useLanguageState } from '../store/appStore';
import { downloadFile } from '../utils/fileUtils';
import { generateDartFileContentForDocs } from '../utils/languageUtils';
import { LanguageFile } from '../types';

const { Title, Paragraph, Text } = Typography;
const { Search } = Input;
const { TextArea } = Input;

const PageContainer = styled.div`
  min-height: 100vh;
  background-color: ${themeConfig.colors.background};
  padding: ${themeConfig.spacing.xl};
`;

const ContentContainer = styled.div`
  max-width: 1400px;
  margin: 0 auto;
`;

const HeaderSection = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: ${themeConfig.spacing.xxl};
`;

const HeaderInfo = styled.div`
  flex: 1;
`;

const MainTitle = styled(Title)`
  color: ${themeConfig.colors.text} !important;
  margin-bottom: ${themeConfig.spacing.sm} !important;
`;

const SubTitle = styled(Paragraph)`
  color: ${themeConfig.colors.textSecondary} !important;
  font-size: ${themeConfig.typography.fontSize.body} !important;
  margin-bottom: 0 !important;
`;

const ActionSection = styled.div`
  display: flex;
  gap: ${themeConfig.spacing.md};
`;

const EditCard = styled(Card)`
  margin-bottom: ${themeConfig.spacing.xl};
  
  .ant-card-head {
    border-bottom: 2px solid ${themeConfig.colors.primary};
  }
`;

const StatisticContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: ${themeConfig.spacing.lg};
  margin-bottom: ${themeConfig.spacing.lg};
`;

const TranslationTableContainer = styled.div`
  .ant-table-thead > tr > th {
    background-color: ${themeConfig.colors.backgroundLight};
    border-bottom: 2px solid ${themeConfig.colors.primary};
    font-weight: ${themeConfig.typography.fontWeight.medium};
  }
  
  .ant-table-tbody > tr:hover > td {
    background-color: #FFF2E8;
  }
  
  .editable-cell {
    position: relative;
  }
  
  .editable-cell-value-wrap {
    padding: 5px 12px;
    cursor: pointer;
    border-radius: ${themeConfig.borderRadius.small};
    transition: all ${themeConfig.transitions.duration} ${themeConfig.transitions.easing};
    
    &:hover {
      background-color: #FFF2E8;
      border: 1px solid ${themeConfig.colors.primary};
    }
  }
`;

const EditModal = styled(Modal)`
  .ant-modal-header {
    background-color: ${themeConfig.colors.primary};
    color: white;
  }
  
  .ant-modal-title {
    color: white;
  }
`;

interface EditLanguagePageProps {
  languageCode: string;
  onBack: () => void;
  onSave: (updatedLanguage: LanguageFile) => void;
}

export const EditLanguagePage: React.FC<EditLanguagePageProps> = ({ 
  languageCode, 
  onBack, 
  onSave 
}) => {
  const { languageFiles } = useLanguageState();
  const [editingLanguage, setEditingLanguage] = useState<LanguageFile | null>(null);
  const [editingData, setEditingData] = useState<Record<string, string>>({});
  const [searchText, setSearchText] = useState('');
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editingKey, setEditingKey] = useState<string>('');
  const [editingValue, setEditingValue] = useState<string>('');
  const [hasChanges, setHasChanges] = useState(false);
  const [jsonText, setJsonText] = useState<string>('');
  const [jsonError, setJsonError] = useState<string>('');
  const [activeTab, setActiveTab] = useState<string>('table');

  // 获取语言名称
  const getLanguageName = (code: string): string => {
    const languageNames: Record<string, string> = {
      'zh': '中文',
      'en': 'English',
      'ar': 'العربية',
      'cs': 'Čeština',
      'da': 'Dansk',
      'de': 'Deutsch',
      'el': 'Ελληνικά',
      'es': 'Español',
      'fa': 'فارسی',
      'fi': 'Suomi',
      'fr': 'Français',
      'ga': 'Gaeilge',
      'he': 'עברית',
      'hr': 'Hrvatski',
      'hu': 'Magyar',
      'it': 'Italiano',
      'ja': '日本語',
      'ko': '한국어',
      'nb': 'Norsk',
      'pl': 'Polski',
      'pt': 'Português',
      'ro': 'Română',
      'ru': 'Русский',
      'sk': 'Slovenčina',
      'sv': 'Svenska',
      'th': 'ไทย',
      'tr': 'Türkçe',
      'uk': 'Українська',
      'vi': 'Tiếng Việt'
    };
    return languageNames[code] || code.toUpperCase();
  };

  // 初始化编辑数据
  useEffect(() => {
    const language = languageFiles.find(f => f.code === languageCode);
    if (language) {
      setEditingLanguage(language);
      setEditingData({ ...language.data });
      // 初始化JSON文本
      setJsonText(JSON.stringify(language.data, null, 2));
    }
  }, [languageCode, languageFiles]);

  // 更新JSON文本当编辑数据变化时
  useEffect(() => {
    if (editingData && Object.keys(editingData).length > 0) {
      setJsonText(JSON.stringify(editingData, null, 2));
    }
  }, [editingData]);

  // 过滤翻译数据
  const filteredData = Object.entries(editingData).filter(([key, value]) => 
    key.toLowerCase().includes(searchText.toLowerCase()) ||
    value.toLowerCase().includes(searchText.toLowerCase())
  );

  // 统计信息
  const stats = {
    totalKeys: Object.keys(editingData).length,
    filledKeys: Object.values(editingData).filter(value => value && value.trim() !== '').length,
    emptyKeys: Object.values(editingData).filter(value => !value || value.trim() === '').length,
    completionRate: Object.keys(editingData).length > 0 ? 
      (Object.values(editingData).filter(value => value && value.trim() !== '').length / Object.keys(editingData).length) * 100 : 0
  };

  // 表格列定义
  const columns = [
    {
      title: '翻译键',
      dataIndex: 'key',
      key: 'key',
      width: 200,
      render: (key: string) => (
        <Text strong style={{ color: themeConfig.colors.text }}>
          {key}
        </Text>
      ),
    },
    {
      title: '翻译值',
      dataIndex: 'value',
      key: 'value',
      render: (value: string, record: { key: string }) => (
        <div className="editable-cell">
          <div 
            className="editable-cell-value-wrap"
            onClick={() => {
              setEditingKey(record.key);
              setEditingValue(value || '');
              setIsEditModalVisible(true);
            }}
          >
            {value && value.trim() !== '' ? (
              <Text style={{ color: themeConfig.colors.text }}>
                {value}
              </Text>
            ) : (
              <Text style={{ 
                color: themeConfig.colors.textSecondary, 
                fontStyle: 'italic' 
              }}>
                (空) - 点击编辑
              </Text>
            )}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_: any, record: { key: string; value: string }) => {
        const isFilled = record.value && record.value.trim() !== '';
        return (
          <Space>
            {isFilled ? (
              <CheckCircleOutlined style={{ color: themeConfig.colors.success }} />
            ) : (
              <ExclamationCircleOutlined style={{ color: themeConfig.colors.warning }} />
            )}
            <Text style={{ 
              fontSize: '12px',
              color: isFilled ? themeConfig.colors.success : themeConfig.colors.warning
            }}>
              {isFilled ? '已填写' : '未填写'}
            </Text>
          </Space>
        );
      },
    },
  ];

  // 保存编辑
  const handleSaveEdit = () => {
    setEditingData(prev => ({
      ...prev,
      [editingKey]: editingValue
    }));
    setHasChanges(true);
    setIsEditModalVisible(false);
    message.success('翻译已保存');
  };

  // 保存所有更改
  const handleSaveAll = () => {
    if (editingLanguage) {
      const updatedLanguage: LanguageFile = {
        ...editingLanguage,
        data: editingData
      };
      onSave(updatedLanguage);
      setHasChanges(false);
      message.success('所有更改已保存');
    }
  };

  // 下载当前语言文件
  const handleDownload = () => {
    if (editingLanguage) {
      const updatedLanguage: LanguageFile = {
        ...editingLanguage,
        data: editingData
      };
      const content = generateDartFileContentForDocs(updatedLanguage);
      downloadFile(content, updatedLanguage.fileName);
      message.success('文件下载成功');
    }
  };

  // JSON编辑相关功能
  const handleJsonChange = (value: string) => {
    setJsonText(value);
    setJsonError('');
  };

  const handleJsonApply = () => {
    try {
      const parsedData = JSON.parse(jsonText);
      
      // 验证JSON结构
      if (typeof parsedData !== 'object' || parsedData === null) {
        throw new Error('JSON必须是一个对象');
      }
      
      // 检查所有值都是字符串
      for (const [key, value] of Object.entries(parsedData)) {
        if (typeof value !== 'string') {
          throw new Error(`键 "${key}" 的值必须是字符串类型`);
        }
      }
      
      setEditingData(parsedData);
      setHasChanges(true);
      setJsonError('');
      message.success('JSON数据已应用');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'JSON格式错误';
      setJsonError(errorMessage);
      message.error(`JSON解析失败: ${errorMessage}`);
    }
  };

  const handleJsonReset = () => {
    if (editingLanguage) {
      setJsonText(JSON.stringify(editingLanguage.data, null, 2));
      setJsonError('');
      message.info('已重置为原始数据');
    }
  };

  const handleJsonCopy = () => {
    navigator.clipboard.writeText(jsonText).then(() => {
      message.success('JSON已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  const handleJsonPaste = () => {
    navigator.clipboard.readText().then((text) => {
      setJsonText(text);
      setJsonError('');
      message.success('已粘贴JSON内容');
    }).catch(() => {
      message.error('粘贴失败');
    });
  };

  // 重置更改
  const handleReset = () => {
    if (editingLanguage) {
      setEditingData({ ...editingLanguage.data });
      setHasChanges(false);
      message.info('已重置所有更改');
    }
  };

  if (!editingLanguage) {
    return (
      <PageContainer>
        <ContentContainer>
          <div style={{ textAlign: 'center', padding: themeConfig.spacing.xxl }}>
            <Title level={3}>语言文件未找到</Title>
            <CustomButton variant="outline" onClick={onBack}>
              返回
            </CustomButton>
          </div>
        </ContentContainer>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      <ContentContainer>
        <HeaderSection>
          <HeaderInfo>
            <MainTitle level={1}>
              编辑语言: {getLanguageName(editingLanguage.code)}
            </MainTitle>
            <SubTitle>
              语言代码: {editingLanguage.code} | 文件: {editingLanguage.fileName}
            </SubTitle>
          </HeaderInfo>
          <ActionSection>
            <CustomButton
              variant="outline"
              icon={<ArrowLeftOutlined />}
              onClick={onBack}
            >
              返回
            </CustomButton>
            <CustomButton
              variant="outline"
              onClick={handleReset}
              disabled={!hasChanges}
            >
              重置
            </CustomButton>
            <CustomButton
              variant="outline"
              icon={<DownloadOutlined />}
              onClick={handleDownload}
            >
              下载
            </CustomButton>
            <CustomButton
              variant="primary"
              icon={<SaveOutlined />}
              onClick={handleSaveAll}
              disabled={!hasChanges}
            >
              保存更改
            </CustomButton>
          </ActionSection>
        </HeaderSection>

        {/* 统计信息 */}
        <EditCard title="翻译统计">
          <StatisticContainer>
            <Statistic
              title="总翻译键"
              value={stats.totalKeys}
              valueStyle={{ color: themeConfig.colors.primary }}
            />
            <Statistic
              title="已填写"
              value={stats.filledKeys}
              valueStyle={{ color: themeConfig.colors.success }}
            />
            <Statistic
              title="未填写"
              value={stats.emptyKeys}
              valueStyle={{ color: themeConfig.colors.warning }}
            />
            <Statistic
              title="完成度"
              value={stats.completionRate.toFixed(1)}
              suffix="%"
              valueStyle={{ 
                color: stats.completionRate === 100 ? themeConfig.colors.success : themeConfig.colors.warning 
              }}
            />
          </StatisticContainer>
        </EditCard>

        {/* 翻译编辑 */}
        <EditCard title="翻译编辑">
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            items={[
              {
                key: 'table',
                label: (
                  <span>
                    <FileTextOutlined />
                    表格编辑
                  </span>
                ),
                children: (
                  <div>
                    <div style={{ marginBottom: themeConfig.spacing.lg }}>
                      <Search
                        placeholder="搜索翻译键或翻译值..."
                        allowClear
                        style={{ width: 400 }}
                        onChange={(e) => setSearchText(e.target.value)}
                      />
                    </div>

                    <TranslationTableContainer>
                      <Table
                        columns={columns}
                        dataSource={filteredData.map(([key, value]) => ({ key, value }))}
                        rowKey="key"
                        pagination={{
                          pageSize: 50,
                          showSizeChanger: true,
                          showQuickJumper: true,
                          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                          pageSizeOptions: ['20', '50', '100', '200'],
                          defaultPageSize: 50,
                        }}
                        scroll={{ x: 600 }}
                      />
                    </TranslationTableContainer>
                  </div>
                )
              },
              {
                key: 'json',
                label: (
                  <span>
                    <CodeOutlined />
                    JSON编辑
                  </span>
                ),
                children: (
                  <div>
                    <div style={{ marginBottom: themeConfig.spacing.lg }}>
                      <Space>
                        <CustomButton
                          variant="outline"
                          icon={<CopyOutlined />}
                          onClick={handleJsonCopy}
                        >
                          复制JSON
                        </CustomButton>
                        <CustomButton
                          variant="outline"
                          onClick={handleJsonPaste}
                        >
                          粘贴JSON
                        </CustomButton>
                        <CustomButton
                          variant="outline"
                          icon={<ReloadOutlined />}
                          onClick={handleJsonReset}
                        >
                          重置
                        </CustomButton>
                        <CustomButton
                          variant="primary"
                          onClick={handleJsonApply}
                          disabled={!!jsonError}
                        >
                          应用JSON
                        </CustomButton>
                      </Space>
                    </div>

                    {jsonError && (
                      <Alert
                        message="JSON格式错误"
                        description={jsonError}
                        type="error"
                        showIcon
                        style={{ marginBottom: themeConfig.spacing.md }}
                      />
                    )}

                    <div style={{ 
                      border: `1px solid ${themeConfig.colors.border}`,
                      borderRadius: themeConfig.borderRadius.small,
                      overflow: 'hidden'
                    }}>
                      <TextArea
                        value={jsonText}
                        onChange={(e) => handleJsonChange(e.target.value)}
                        rows={20}
                        placeholder="请粘贴或编辑JSON内容..."
                        style={{ 
                          fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
                          fontSize: '14px',
                          lineHeight: '1.5',
                          border: 'none',
                          resize: 'vertical'
                        }}
                      />
                    </div>

                    <div style={{ 
                      marginTop: themeConfig.spacing.sm,
                      padding: themeConfig.spacing.sm,
                      backgroundColor: themeConfig.colors.backgroundLight,
                      borderRadius: themeConfig.borderRadius.small,
                      fontSize: themeConfig.typography.fontSize.caption,
                      color: themeConfig.colors.textSecondary
                    }}>
                      💡 提示：您可以粘贴其他JSON文件的键值对，系统会自动验证格式并应用到当前语言文件
                    </div>
                  </div>
                )
              }
            ]}
          />
        </EditCard>

        {/* 编辑模态框 */}
        <EditModal
          title={`编辑翻译: ${editingKey}`}
          open={isEditModalVisible}
          onCancel={() => setIsEditModalVisible(false)}
          footer={[
            <Button key="cancel" onClick={() => setIsEditModalVisible(false)}>
              取消
            </Button>,
            <Button key="save" type="primary" onClick={handleSaveEdit}>
              保存
            </Button>
          ]}
          width={600}
        >
          <div>
            <div style={{ marginBottom: themeConfig.spacing.md }}>
              <Text strong>翻译键：</Text>
              <Tag color={themeConfig.colors.primary}>{editingKey}</Tag>
            </div>
            
            <Form.Item label="翻译值">
              <TextArea
                value={editingValue}
                onChange={(e) => setEditingValue(e.target.value)}
                rows={4}
                placeholder="请输入翻译内容..."
                style={{ 
                  borderRadius: themeConfig.borderRadius.small,
                  borderColor: themeConfig.colors.border
                }}
              />
            </Form.Item>
            
            <div style={{ 
              padding: themeConfig.spacing.sm,
              backgroundColor: themeConfig.colors.backgroundLight,
              borderRadius: themeConfig.borderRadius.small,
              fontSize: themeConfig.typography.fontSize.caption,
              color: themeConfig.colors.textSecondary
            }}>
              💡 提示：留空表示该翻译项未填写，保存后状态将更新
            </div>
          </div>
        </EditModal>
      </ContentContainer>
    </PageContainer>
  );
};
